<template>
  <div>
    <!-- <TodoHeader :addTodo="addTodo" /> -->
    <TodoHeader @addTodo="addTodo" />
    <!-- <TodoList :todoList="todoList" :checkTodo="checkTodo" :deleteTodo="deleteTodo" /> -->
    <TodoList :todoList="todoList" />
    <!-- <TodoFooter :todoList="todoList" :chooseAll="chooseAll" :delCompleted="delCompleted" /> -->
    <TodoFooter :todoList="todoList" @chooseAll="chooseAll" @delCompleted="delCompleted" />
  </div>
</template>

<script>
import TodoHeader from './components/TodoHeader.vue';
import TodoList from './components/TodoList.vue';
import TodoFooter from './components/TodoFooter.vue';

import PubSub from 'pubsub-js'

export default {
  name: 'App',
  components: {
    TodoHeader,
    TodoList,
    TodoFooter
  },
  data() {
    return {
      todoList: JSON.parse(localStorage.getItem('todoList')) || []
    }
  },
  // 为什么用watch实现本地化存储？
  watch: {
    todoList: {
      deep: true,
      handler(val) {
        localStorage.setItem('todoList', JSON.stringify(val))
      }
    }
  },
  mounted() {
    this.$bus.$on('checkTodo', this.checkTodo)
    // this.$bus.$on('deleteTodo', this.deleteTodo)
    this.pubId = PubSub.subscribe('deleteTodo', this.deleteTodo)
    this.$bus.$on('editTodo', this.editTodo)
  },
  beforeDestroy() {
    PubSub.unsubscribe(this.pubId)
  },
  methods: {
    // 新增todo
    addTodo(todo) {
      this.todoList.unshift(todo)
    },
    // 勾选
    checkTodo(id) {
      this.todoList.forEach(todo => {
        if (todo.id === id) {
          todo.completed = !todo.completed
        }
      })
    },
    // 删除
    deleteTodo(_, id) {
      this.todoList = this.todoList.filter(todo => {
        return todo.id !== id
      })
    },
    // 全选or全不选
    chooseAll(val) {
      this.todoList.forEach(todo => {
        todo.completed = val
      })
    },
    // 删除已勾选
    delCompleted() {
      this.todoList = this.todoList.filter(todo => {
        return !todo.completed
      })
    },
    // 编辑
    editTodo(id, val) {
      this.todoList.forEach(todo => {
        if (todo.id === id) {
          todo.title = val
        }
      })
    }
  }
}
</script>